<template>
  <div>
    <el-upload
      :class="{Exhibition:filelist.length>0}"
      action="#"
      :file-list="filelist"
      list-type="picture-card"
      :on-preview="onpreview"
      :on-remove="onRemove"
      :http-request="upload"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="Showpercent" style="width:146px" :text-inside="true" :stroke-width="18" :percentage="percent" />
    <el-dialog title="预览" :visible="Showdao" @close="Showdao=false">
      <img :src="imgUrl" alt="" class="doop">
    </el-dialog>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  SecretId: 'AKID62h5D4f05tSmpc8NL1QYOyHzSfcIhphJ',
  SecretKey: 'MRFm21jAKDpAE2Zqra2E8l7C0XnmVxzl'
})
export default {
  data() {
    return {
      imgUrl: '',
      Showdao: false,
      percent: 0,
      Showpercent: false,
      filelist: []
    }
  },
  methods: {
    // 点击文件列表中已上传的文件时触发
    onpreview(file) {
      // console.log(file)
      this.imgUrl = file.url
      this.Showdao = true
    },
    // 删除图片触发钩子
    onRemove(file, newfileList) {
      this.filelist = newfileList
    },
    // 改变文件状态是触发
    onChange(file, newfileList) {
      this.filelist = newfileList
    },
    // 文件上传前触发用于校验文件
    beforeUpload(file) {
    //  // console.log(52, file)
      const maxsize = 2 * 1024 * 1024
      if (file.size > maxsize) {
        this.$message.warning('只能上传2M以下的文件')
        return false
      }
      const whiteLiat = ['image/jpeg', 'image/png']
      if (!whiteLiat.includes(file.type)) {
        this.$message.warning('只能上传jpeg/png格式的文件')
        return false
      }
    },
    //   覆盖默认的上传行为,上传触发
    upload(params) {
      // console.log(71, params)
      this.Showpercent = true
      cos.putObject({
        // 储存桶名称
        Bucket: 'hr67-1307764451',
        // 地区代码
        Region: 'ap-nanjing',
        // 储存后的文件名
        Key: params.file.name,
        // 默认标准储存不用修改
        StorageClass: 'STANDARD',
        // 上传文件对象
        Body: params.file, // 上传文件对象

        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          //  percent 是0-1
          this.percent = progressData.percent * 100
        }
        // 上传成功回调
      }, (err, data) => {
        // console.log(89, err) // 失败
        // console.log(90, data)// 成功
        if (!err) {
          this.filelist[0].url = 'http://' + data.Location
          this.filelist[0].status = 'success'
          setTimeout(() => {
            this.Showpercent = false
          }, 1000)
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.Exhibition {
  ::v-deep .el-upload--picture-card {
        display: none;
    }
}
.doop {
   max-width: 100%;
}
 ::v-deep .el-dialog__body {
    text-align: center;
}
</style>
